var util = require("../../utils/time-utils.js");
var home = require("../../utils/util.js");
var url = home.home;
var url2 = home.home2;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsData: {},
    type: '',
    xuanDay: new Date().getFullYear()+'/'+(new Date().getMonth()+1)+'/'+new Date().getDate(),
    xianDay: "选择下方日期和时间段",
    xuanze: "到店指派",
    xuanzeid: 0,
    projectId: 0,
    height:300,
    page: 1, //分页
    state: wx.getStorageSync('state'),
    states: false,
    btnState:false,
    btnState2:true,
    shopData: {
        'storeName': '', //店铺名称
        'storePhone': '', //店铺手机号
        'storeVideo': '', //店铺视频,
        'lat': '', //纬度
        'lng': '', //经度
        'id': '', //店铺ID
        'businessEnd': '', //营业结束时间
        'businessStart': '', //营业开始时间
    }, //店铺信息
    listData: [], //列表数据
    //popupShow: false,//底部弹出
    daka:false,
    mode:'bottom',//模式
    radius:'20rpx',
    closeable:true,
    maskClosable:true,
    closeIconPos:'top-right',
    backgroundColor:'#e8e8e8',
    bgcolor: home.getKey('bgcolor'),
    //
    selectWeek:0,
    timeBean:{},
    //
    currentTime:"-1",
    xuanTime:"0:00-0:00",
    timeArr: [
      // { "time": "08:00-09:00", "status": "guoqi" }, 
      // { "time": "09:00-10:00", "status": "" }, 
      // { "time": "10:00-11:00", "status": "" }, 
      // { "time": "11:00-12:00", "status": "" }, 
      // { "time": "12:00-13:00", "status": "" }, 
      // { "time": "13:00-14:00", "status": "" }, 
      // { "time": "14:00-15:00", "status": "" }, 
      // { "time": "15:00-16:00", "status": "" }, 
      // { "time": "16:00-17:00", "status": "" },
      // { "time": "17:00-18:00", "status": "" }, 
      // { "time": "18:00-19:00", "status": "" },
      ]
  },

  openDrawer(){
    this.setData({
      daka:true
    })
    this.getShopList();
  },
  closeDrawer(){
    this.setData({
      daka:false
    })
  },

  selectTime:function(event){
    //时间段点击事件https://www.laike.net/article-28-59059-0.html
    this.setData({
     currentTime: event.currentTarget.dataset.tindex,
     xianDay: this.data.xuanDay+' '+event.currentTarget.dataset.time,
     xuanTime:event.currentTarget.dataset.time
    })
    //console.log(this.data.xuanDay+' '+event.currentTarget.dataset.time)
   },

    /**
     * 调起手机拨号
     */
    callPhone() {
        let shopData = this.data.shopData;
        wx.makePhoneCall({
          phoneNumber: shopData.storePhone //仅为示例，并非真实的电话号码
        })
    },

  //确认预约
  addCar() {
    wx.showLoading({
      title: '加载中...',
    });
    this.setData({
      btnState2: false
    });
    let that = this;
    let goodsData = this.data.goodsData;
    if (that.data.currentTime == -1 || that.data.xianDay == '选择下方日期和时间段') {
      that.setData({
        btnState2: true,
      })
      home.wxMessage('请选择预约日期和时间','none');
      return false;
    }
    wx.request({
      url: url + 'app/prebookSave',
      data: {
        memberId:home.getKey('userId'),
        storeId:home.getKey('storeId'),
        //createBy:'system',
        day:that.data.xuanDay,
        yuyueTime:that.data.xuanTime,
        projectId:goodsData.projectId,
        //projectName:goodsData.projectName,
        employeeId:that.data.xuanzeid,
      },
      method: 'GET',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        let msg = '';
        let icon = '';
        if (res.data.code == 200) {
          //msg = '预约成功';
          //icon = 'success';
          wx.navigateTo({
            url: 'pay',
          })
          // that.setData({
          //   goodsData: goodsData,
          //   btnState1:false,
          // });
        } else {
          that.setData({
            btnState2: true,
          })
          msg = '预约失败，请点右侧电话联系店铺';
          icon = 'none';
          //请求接口返回时间段（带选择人和日期）
          that.getTimeList();
        }
        wx.showToast({
          title: msg,
          icon: icon
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let goodsData = JSON.parse(options.info);
    goodsData.num = 0;
    this.setData({
      goodsData: goodsData,
      states:false,
      state: wx.getStorageSync('state'),
    });
  },
  // 底部弹出
  // popup: function () {
  //   this.getShopList();
  //   this.setData({
  //     popupShow: !this.data.popupShow
  //   })
  // },
  //获取技师列表
  getShopList() {
    let requestUrl = '';
    requestUrl = url + 'app/listEmployee'
    let that = this;
    wx.request({
      url: requestUrl,
      data: {
        storeId: home.getKey('storeId'),
        pageNo: that.data.page,
        memberId: home.getKey('userId'),
      },
      method: 'GET',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        if (res.data.code == 200) {
          let listData = res.data.result.records;
          console.log(listData);
          if (that.data.page == 1) {
            listData = res.data.result.records;
          } else {
            for (let i = 0; i < res.data.result.records.length; i++) {
               listData.push(res.data.result.records[i]);
            }
          }
          that.setData({
            listData: listData
          });
        } else {
          home.wxMessage(res.data.message, 'none');
        }
      }
    })
  },
  xuanze:function(event){
    //请求接口返回时间段（带选择人和日期）
    this.setData({
      xuanze: event.currentTarget.dataset.inventory,
      xuanzeid: event.currentTarget.dataset.id,
      xianDay: "选择下方日期和时间段",
      currentTime:"-1",
      //popupShow: !this.data.popupShow,
      // timeArr: [
      //   { "time": "08:00-09:00", "status": "guoqi" }, 
      //   { "time": "09:00-10:00", "status": "guoqi" }, 
      //   { "time": "10:00-11:00", "status": "" }, 
      //   { "time": "11:00-12:00", "status": "" }, 
      //   { "time": "12:00-13:00", "status": "" }, 
      //   { "time": "13:00-14:00", "status": "" }, 
      //   { "time": "14:00-15:00", "status": "" }, 
      //   { "time": "15:00-16:00", "status": "" }, 
      //   { "time": "16:00-17:00", "status": "" },
      //   { "time": "17:00-18:00", "status": "" }, 
      //   { "time": "18:00-19:00", "status": "" },
      //   ]
     })
     //请求接口返回时间段（带选择人和日期）
     this.getTimeList();
  },
  noxuanze:function(){
    this.setData({
      daka:false,
      xuanze: '到店指派',
      xuanzeid: 0,
      xianDay: "选择下方日期和时间段",
      currentTime:"-1",
      //popupShow: !this.data.popupShow,
     })
     //请求接口返回时间段（带选择人和日期）
     this.getTimeList();
  },
    //
    /**
     * 点击了上一周，选择周数字减一，然后直接调用工具类中一个方法获取到数据
     */
    lastWeek:function(e){   
      var selectWeek = --this.data.selectWeek;
      var timeBean = this.data.timeBean
      timeBean = util.getWeekDayList(selectWeek,timeBean)
      //console.log(timeBean['ri']);//选中日期
      if(new Date(timeBean['ri']).getTime() + 3600 * 1000 * 24<new Date().getTime())
      {
        home.wxMessage('不能预约之前的日期','none');
        return false;
      }
      if (selectWeek != 0) {
        //timeBean.selectDay = 0;
      }
      this.setData({
        xuanDay:timeBean['ri'],
        xianDay: "选择下方日期和时间段",
        currentTime:"-1",
        timeBean,
        selectWeek
      })
      //请求接口返回时间段（带选择人和日期）
      this.getTimeList();
    },
  
    /**
     * 点击了下一周，选择周数字加一，然后直接调用工具类中一个方法获取到数据
     */
    nextWeek:function(e){
      var selectWeek = ++this.data.selectWeek;
      var timeBean = this.data.timeBean
      timeBean = util.getWeekDayList(selectWeek,timeBean)
      //console.log(timeBean['ri']);//选中日期
      if (selectWeek != 0){
        //timeBean.selectDay = 0;
      }
      this.setData({
        xuanDay:timeBean['ri'],
        xianDay: "选择下方日期和时间段",
        currentTime:"-1",
        timeBean,
        selectWeek
      })
      //请求接口返回时间段（带选择人和日期）
      this.getTimeList();
    },
  
    /**
     * 选中了某一日，改变selectDay为选中日
     */ 
    dayClick:function(e){
      var timeBean = this.data.timeBean
      if(new Date(timeBean.weekDayList[e.detail].nianyue+'/'+timeBean.weekDayList[e.detail].day).getTime() + 3600 * 1000 * 24<new Date().getTime())
      {
        home.wxMessage('不能预约之前的日期','none');
        return false;
      }
      timeBean.selectDay = e.detail;
      //console.log(e.detail);
      //console.log(timeBean.weekDayList[e.detail].nianyue+'-'+timeBean.weekDayList[e.detail].day);//选中日期
      this.setData({
        xuanDay:timeBean.weekDayList[e.detail].nianyue+'/'+timeBean.weekDayList[e.detail].day,
        xianDay: "选择下方日期和时间段",
        currentTime:"-1",
        timeBean,
      })
      //请求接口返回时间段（带选择人和日期）
      this.getTimeList();
    },
    //


        //小程序授权
        login() {
          wx.showLoading({
            title: '加载中...',
          })
          this.setData({
            btnState:false,
          });
          let that = this;
          wx.getUserProfile({
            desc: '用于完善会员资料',
            success: function (ress) {
              wx.login({
                success(res) {
                  wx.request({
                    url: 'https://kyz.fbhkj.com/fubaihui/app/xcx/updateUserNickName?storeId=' + app.globalData.storeId + '&code=' + res.code + '&xcxOpenId=' + wx.getStorageSync('openId') + '&unionId=' + wx.getStorageSync('unionId') + '&nickName' + ress.userInfo.nickName + '&headPortrait=' + ress.userInfo.avatarUrl + '&sex=保密',
                    data: {
                      storeId: app.globalData.storeId,
                      nickName: ress.userInfo.nickName,
                      headPortrait: ress.userInfo.avatarUrl,
                      sex: '保密',
                      xcxOpenId: wx.getStorageSync('openId'),
                      unionId: wx.getStorageSync('unionId')
                    },
                    method: 'POST',
                    header: {
                      "content-type": "application/json", // 默认
                    },
                    success: function (rea) {
                      if (rea.data.code == 200) {
                        wx.hideLoading({
                          success: (res) => {
                            that.setData({
                              btnState: true,
                              states:false,
                              state:2
                            })
                          },
                        })
                        wx.setStorageSync('nickName', ress.userInfo.nickName);
                        wx.setStorageSync('avatar', ress.userInfo.avatarUrl);
                        that.setData({
                          state: 2
                        });
                        wx.setStorageSync('state', 2);
                      }
                    }
                  })
                }
              })
            },
            fail: function (res) {
              that.setData({
                btnState: true,
              })
              wx.showToast({
                title: '授权失败',
                icon: 'none',
                duration: 1500,
              })
            }
          })
        },
        register() {
          wx.showLoading({
              title: '加载中...',
          });
          let that = this;
          wx.login({
              success(res) {
                  wx.request({
                      url: 'https://kyz.fbhkj.com/fubaihui/app/xcx/register?storeId=' + app.globalData.storeId + '&code=' + res.code,
                      data: {
                          storeId: app.globalData.storeId,
                          code: res.code
                      },
                      method: 'POST',
                      header: {
                          "content-type": "application/json", // 默认
                      },
                      success: function (rea) {
                          if (rea.data.code == 200) {
                              let states = false;
                              if (!rea.data.result.hasPhone) {
                                  that.setData({
                                      state: 1
                                  });
                                  //home.setKey('state', 1);
                                 // wx.setStorageSync('state', 1);
                              } else if (!rea.data.result.hasNickName) {
                                  states = true;
                                  that.setData({
                                      state: 0
                                  });
                                  //home.setKey('state', 0);
                                  //wx.setStorageSync('state', 0);
                              }
                              home.setKey('subscribeTencent', rea.data.result.subscribeTencent);
                              home.setKey('hasNickName', rea.data.result.hasNickName);
                              home.setKey('hasPhone', rea.data.result.hasPhone);
                              home.setKey('userId', rea.data.result.member.id);
                              home.setKey('phone', rea.data.result.member.phone);
                              home.setKey('avatar', rea.data.result.member.avatarUrl);
                              home.setKey('status', rea.data.result.member.status);
                              home.setKey('discount', rea.data.result.member.discount);
                              home.setKey('nickName', rea.data.result.member.nickName);
                              home.setKey('openId', rea.data.result.member.xcxOpenId);
                              home.setKey('unionId', rea.data.result.member.unionId);
                              let states1 = false;
                              if (rea.data.result.hasPhone && rea.data.result.hasNickName) {
                                  states1 = !rea.data.result.subscribeTencent;
                                  that.setData({
                                      state: 2
                                  });
                                  home.setKey('state', 2);
                                  wx.setStorageSync('state', 2);
                                  that.getUserInfos();
                              }
                              that.setData({
                                  states: states,
                                  states1: states1,
                              })
                              wx.hideLoading({
                                  success: (res) => {
  
                                  },
                              })
                          } else {
                              home.wxMessage(rea.data.message, 'none');
                          }
                      }
                  })
              }
          })
      },
        getPhoneNumber(e) {
          console.log(e.detail);
          wx.showLoading({
            title: '加载中...',
          });
          this.setData({
            btnState1:false,
          })
          if (e.detail.code == undefined) {
            wx.showToast({
              title: '请授权获取手机号',
              icon: 'none',
              duration: 1500,
            })
            wx.setStorageSync('state', 1);
            this.setData({
              btnState1:true,
            })
            return false;
          }
          let that = this;
          wx.request({
            url: 'https://kyz.fbhkj.com/fubaihui/app/xcx/getPhone?storeId=' + app.globalData.storeId + '&code=' + e.detail.code + '&xcxOpenId=' + wx.getStorageSync('openId') + '&unionId=' + wx.getStorageSync('unionId'),
            data: {
              storeId: app.globalData.storeId,
              code: e.detail.code,
              xcxOpenId:wx.getStorageSync('openId'),
              unionId:wx.getStorageSync('unionId')
            },
            method: 'POST',
            header: {
              "content-type": "application/json", // 默认
            },
            success: function (res) {
              if (res.data.code == 200) {
                wx.hideLoading({
                  success: (res) => {
                    that.setData({
                      btnState1: true,
                    });
                  },
                })
                wx.setStorageSync('phone', res.data.result.phone);
                wx.setStorageSync('userId', res.data.result.id);
                let state = 2;
                
                if (!wx.getStorageSync('hasNickName')) {
                  state = 0;
                }
                
                that.setData({
                  state: state
                });
                wx.setStorageSync('state', state);
              } else {
                wx.showToast({
                  title: '获取失败',
                  icon: 'none',
                  duration: 1500,
                })
              }
            }
          })
        },
        onClose1() {
          this.setData({
              states: false,
          })
      },

//获取时间段列表
getTimeList() {
  let requestUrl = '';
  requestUrl = url + 'app/prebookTime'
  let that = this;
  wx.request({
    url: requestUrl,
    data: {
      storeId: home.getKey('storeId'),
      day: that.data.xuanDay,
      projectId: that.data.goodsData.projectId,
      employeeId: that.data.xuanzeid,
      memberId: home.getKey('userId'),
    },
    method: 'GET',
    header: {
      "content-type": "application/json", // 默认
    },
    success: function (res) {
      if (res.data.code == 200) {
        //console.log(res.data.result);
        for (let i = 0; i < res.data.result.length; i++) {
          if (res.data.result[i].status==0) {
            res.data.result[i].status = 'guoqi';//过期不能预约
          }
        }
        that.setData({
          timeArr: res.data.result
        });
      } else {
        home.wxMessage(res.data.message, 'none');
      }
    }
  })
},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
      //请求接口返回时间段（带选择人和日期）
      this.getTimeList();
      //
      this.setData({
        timeBean: util.getWeekDayList(this.data.selectWeek),
        // timeArr: [
        //   { "time": "08:00-09:00", "status": "guoqi" }, 
        //   { "time": "09:00-10:00", "status": "guoqi" }, 
        //   { "time": "10:00-11:00", "status": "guoqi" }, 
        //   { "time": "11:00-12:00", "status": "" }, 
        //   { "time": "12:00-13:00", "status": "" }, 
        //   { "time": "13:00-14:00", "status": "" }, 
        //   { "time": "14:00-15:00", "status": "" }, 
        //   { "time": "15:00-16:00", "status": "" }, 
        //   { "time": "16:00-17:00", "status": "" },
        //   { "time": "17:00-18:00", "status": "" }, 
        //   { "time": "18:00-19:00", "status": "" },
        //   ]
      })
      //
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          height:res.windowWidth,
          btnState2: true,
          page:1,
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let page = this.data.page;
    this.setData({
      page: ++page
    });
    this.getShopList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})